package com.edianping.store;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.log4j.Logger;

import com.edianping.util.LogCode;

public class UserLoginEventDBStore extends AbstractDBStore {
	protected static Logger log = Logger.getLogger(AbstractDBStore.class);
	
	/**
	 * Get the user login count in the last 30 days
	 * @param userId
	 * @param days
	 * @return
	 */
	public static int GetUserLoginCountById( int userId, int days ) {
		int result = 0;
		Connection conn = null;
		Statement stmt = null;
		String sql = "SELECT count(*), DATE_FORMAT(login_time , '%Y-%m-%d') AS dd "+
			" FROM  `user_login_event`"+
			" WHERE user_id ="+userId+
			" AND DATEDIFF( NOW( ) , login_time ) <"+days+
			" group by dd";

		try {
			conn = pool.getConnection();
			stmt = conn.createStatement();

			ResultSet rs = stmt.executeQuery(sql);

			while (rs.next()) {
				result += 1;
			}

			rs.close();
			stmt.close();

		} catch (Exception e) {
			log.error("[[" + LogCode.E_DB_SQL_ERROR + "]], SQL:[" + sql + "]", e);
		} finally {
			if (conn != null)
				pool.checkin(conn);
		}

		return result;
	}
	
	//just for test
//	public static void main(String[] args) {
//		int res = UserLoginEventDBStore.GetUserLoginCountById(636, 30);
//		System.out.println( res );
//	}
}
